package com.example.li893.a2048demo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.TextView;

import java.util.ArrayList;

public class RankActivity extends Activity {
    private String name;
    private int grade;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rank);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        Intent intent = getIntent();
        name = intent.getStringExtra("usersName");
        grade = intent.getIntExtra("grade", 0);
        new Thread(runnablePost).start();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(runnableGet).start();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(RankActivity.this, StartActivity.class);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode, event);
    }

    @SuppressLint("HandlerLeak")
    Handler GetHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            TextView textView = findViewById(R.id.rankList);
            ArrayList<String> getRank = data.getStringArrayList("rank");
            StringBuilder result = new StringBuilder();
            if (getRank != null) {
                for (String s : getRank) {
                    result.append(s);
                }
            }
            textView.setText(result);
            textView.setTextSize(30);
        }
    };


    Runnable runnableGet = new Runnable() {
        @Override
        public void run() {
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putStringArrayList("rank", new GetRun().run());
            msg.setData(data);
            GetHandler.sendMessage(msg);
        }
    };

    Runnable runnablePost = new Runnable() {
        @Override
        public void run() {
            if (name != null && name != "")
                new PostRun(name, grade).run();
        }

    };
}
